<template>
  <div class="login-wrapper">
    <div class="background-overlay"></div>
    <el-card class="login-card" shadow="always">
      <h2 class="title">欢迎进入 MBTI 测试系统</h2>
      <el-form :model="form" ref="loginForm" label-position="top" status-icon>
        <el-form-item label="学号" prop="studentNo" :rules="[{ required: true, message: '请输入学号', trigger: 'blur' }]">
          <el-input v-model="form.studentNo" placeholder="请输入学号" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password clearable />
        </el-form-item>
        <el-form-item class="button-group">
          <el-button type="primary" @click="onLogin" round>登录</el-button>
          <el-button type="success" @click="$router.push('/register')" round>注册账号</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const form = reactive({
  studentNo: '',
  password: ''
});

const onLogin = async () => {
  if (!form.studentNo || !form.password) {
    ElMessage.error('请完整填写学号和密码');
    return;
  }

  try {
    const res = await axios.post('http://localhost:8081/api/students/login', form);
    const studentInfo = res.data;

    ElMessage.success('登录成功');
    sessionStorage.setItem('studentInfo', JSON.stringify(studentInfo));
    sessionStorage.setItem('studentId', studentInfo.id);
    sessionStorage.setItem('loggedIn', 'true');

    window.location.href = '/test';
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '登录失败，请检查输入');
  }
};
</script>

<style scoped>
.login-wrapper {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #c3ecff, #fce2e2);
  position: relative;
  overflow: hidden;
}

.background-overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at top right, rgba(255, 255, 255, 0.3), transparent 70%),
  radial-gradient(circle at bottom left, rgba(255, 255, 255, 0.3), transparent 70%);
  pointer-events: none;
}

.login-card {
  width: 400px;
  padding: 30px 40px;
  border-radius: 16px;
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
  background-color: #ffffffcc;
  z-index: 1;
  position: relative;
}

.title {
  text-align: center;
  font-weight: 700;
  font-size: 24px;
  margin-bottom: 30px;
  color: #333;
}

.el-form-item {
  margin-bottom: 24px;
}

.button-group {
  display: flex;
  justify-content: space-between;
}
</style>
